// @lcpr-before-debug-begin

// @lcpr-before-debug-end

// @before-stub-for-debug-begin
#include <vector>
#include <string>

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=450 lang=cpp
 * @lcpr version=30204
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lcpr-template-start
using namespace std;
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// @lcpr-template-end
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start

class Solution
{
public:
    TreeNode *deleteNode(TreeNode *root, int key)
    {
        return innerDeleteNode(root, key);
    }

    TreeNode *innerDeleteNode(TreeNode *root, int key)
    {
        if (root == nullptr)
            return nullptr;

        if (root->val == key)
        {
            // 左子树为空，就只剩下右子树了
            if (root->left == nullptr)
                return root->right;
            // 右子树挂到左子树上
            auto l = root->left;
            while (l->right != nullptr)
                l = l->right;
            l->right = root->right;
            return root->left;
        }
        if (root->val < key)
        {
            root->right = innerDeleteNode(root->right, key);
        }
        root->left = innerDeleteNode(root->left, key);
        return root;
    }
};
// @lc code=end

/*
// @lcpr case=start
// [5,3,6,2,4,null,7]\n3\n
// @lcpr case=end

// @lcpr case=start
// [5,3,6,2,4,null,7]\n0\n
// @lcpr case=end

// @lcpr case=start
// []\n0\n
// @lcpr case=end

 */
